import {
	SCN_CUST_ACTION_SCODE_KEY,
	SCN_CUST_EX_SCODE_KEY,
	android_content_Context,
	android_content_Intent,
	android_content_IntentFilter,
	BroadcastReceiver,
	BroadcastReceiveEvent,
	brands,
	models,
	scanInfos
} from './index.d';

/**
 * 使用扫描对象
 */
export function useScan() {
	// js对象转json数据:  JSON.stringify();
	// json数据转js对象:  JSON.parse();

	let scanInstance = null;
	// console.log('useI18n', getApp().globalData);
	const globalData = getApp().globalData;
	if (globalData.scanClient) {
		scanInstance = {
			scan: globalData.scanClient
		};
		// console.log('useScan_global', scanInstance);
		return scanInstance;
	} else {
		globalData.scanClient = createScan();
		scanInstance = {
			scan: globalData.scanClient
		};
		// console.log('useScan_create', scanInstance);
		return scanInstance;
	}
};

/** 创建扫描 */
export function createScan() {
	// 创建实例并挂载系统信息
	const instance = new Object();
	instance.systemInfo = uni.getSystemInfoSync();
	// console.log('createScan', instance);

	// 在 Scan 实例上挂载 getScanActionInfo 方法
	instance.getScanActionInfo = function() {
		// console.log('createScan_getScanActionInfo', instance.systemInfo);
		let scanActionInfo = uni.getStorageSync(SCN_CUST_ACTION_SCODE_KEY);
		if (scanActionInfo === undefined || scanActionInfo === null || scanActionInfo === '') {
			if (instance.systemInfo.brand) {
				for (let i = 0; i < scanInfos.length; i++) {
					const scanInfo = scanInfos[i];
					// console.log('getScanActionInfo', scanInfo);
					if (scanInfo && scanInfo.value) {
						if (scanInfo.value.toUpperCase() === instance.systemInfo.brand.toUpperCase()) {
							scanActionInfo = scanInfo.scanAction;
						}
					}
				}
			}
		}
		return scanActionInfo;
	};
	// 在 Scan 实例上挂载 getScanActionInfo 方法
	instance.setScanActionInfo = function(value) {
		uni.setStorageSync(SCN_CUST_ACTION_SCODE_KEY, value);
	};

	// 在 Scan 实例上挂载 getScanDataInfo 方法
	instance.getScanDataInfo = function() {
		// console.log('createScan_getScanDataInfo', instance.systemInfo);
		let scanDataInfo = uni.getStorageSync(SCN_CUST_EX_SCODE_KEY);
		if (scanDataInfo === undefined || scanDataInfo === null || scanDataInfo === '') {
			if (instance.systemInfo.brand) {
				for (let i = 0; i < scanInfos.length; i++) {
					const scanInfo = scanInfos[i];
					// console.log('getScanDataInfo', scanInfo);
					if (scanInfo && scanInfo.value) {
						if (scanInfo.value.toUpperCase() === instance.systemInfo.brand.toUpperCase()) {
							scanDataInfo = scanInfo.scanData;
						}
					}
				}
			}
		}
		return scanDataInfo;
	};
	// 在 Scan 实例上挂载 setScanDataInfo 方法
	instance.setScanDataInfo = function(value) {
		uni.setStorageSync(SCN_CUST_EX_SCODE_KEY, value);
	};

	//#ifdef APP-PLUS
	instance.mainActivity = plus.android.runtimeMainActivity(); //获取activity
	// let context = plus.android.importClass('android.content.Context'); //上下文
	let context = plus.android.importClass(android_content_Context); //上下文
	// var Intent = plus.android.importClass('android.content.Intent');
	var Intent = plus.android.importClass(android_content_Intent);
	// let IntentFilter = plus.android.importClass('android.content.IntentFilter');
	let IntentFilter = plus.android.importClass(android_content_IntentFilter);
	var filter = new IntentFilter();
	// filter.addAction("com.android.server.scannerservice.broadcast");	//监听扫描
	filter.addAction(instance.getScanActionInfo()); //监听扫描

	// // instance.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
	// // 	onReceive: doReceive
	// // });
	// instance.receiver = plus.android.implements(BroadcastReceiver, {
	// 	onReceive: doReceive
	// });

	// 样例
	// function doReceive(context, intent) {
	// 	plus.android.importClass(intent); //通过intent实例引入intent类，方便以后的‘.’操作
	// 	let code = intent.getStringExtra("barcode_string"); // 换你的广播标签
	// 	console.log(code);

	// 	instance.mainActivity.unregisterReceiver(instance.receiver); //取消监听  
	// }

	// 样例
	// function queryCode(context, intent) {
	// 	//防重复  
	// 	if (codeQueryTag) return false;
	// 	codeQueryTag = true;
	// 	setTimeout(function() {
	// 		codeQueryTag = false;
	// 	}, 150);
	// 	var id = code
	// 	console.log('id:', id)
	// 	uni.$emit('scancodedate', {
	// 		code: id
	// 	})
	// }
	//#endif

	let codeQueryTag = false;

	// 在 Scan 实例上挂载 stop 方法
	instance.stop = function() {
		//#ifdef APP-PLUS
		instance.mainActivity.unregisterReceiver(instance.receiver); //取消监听
		// 设置对象自动回收
		plus.android.autoCollection(instance.receiver);
		//#endif
	};
	// 在 Scan 实例上挂载 start 方法
	instance.start = function(callback, emitEvent = false) {
		instance.stop(); //取消监听

		//#ifdef APP-PLUS
		instance.receiver = plus.android.implements(BroadcastReceiver, {
			//扫描后触发事件
			onReceive: function(context, intent) {
				plus.android.importClass(intent); //通过intent实例引入intent类，方便以后的‘.’操作
				let code = intent.getStringExtra(instance.getScanDataInfo()); // 换你的广播标签
				// console.log(code);
				//防重复  
				if (codeQueryTag === true) {
					return;
				}
				codeQueryTag = true;
				setTimeout(function() {
					codeQueryTag = false;
				}, 150);
				// console.log('id:', code);
				// 提交APP事件
				if (emitEvent === true) {
					uni.$emit(BroadcastReceiveEvent, {
						context: context,
						intent: intent,
						data: code
					});
					// // APP事件使用样例：建议放在onShow中
					// uni.$off(BroadcastReceiveEvent); // 每次进来先 移除全局自定义事件监听器  
					// uni.$on(BroadcastReceiveEvent, function(data) {
					// 	console.log('你想要的code：', data.code)
					// });
				}
				// 会调事件
				if (callback && typeof callback === 'function') {
					callback({
						context: context,
						intent: intent,
						data: code
					});
				}

			},
		});

		instance.mainActivity.registerReceiver(instance.receiver, filter); //注册监听
		//#endif
	};

	return instance;
}

/** 扫描客户端 */
const scanClient = createScan();

export default scanClient;
